package com.net.utils;


import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * Date: 13-10-29
 * Time: 16:47
 */
public class Socket {


    private String ip;

    private int port;

    private int timeout_conn;

    private int timeout_read;

    private Map configMap = new HashMap();

    public Socket(String ip, int port, int timeout_conn, int timeout_read) {
        this.ip = ip;
        this.port = port;
        this.timeout_conn = timeout_conn;
        this.timeout_read = timeout_read;
    }

    public static final String TCP_IP = "ip";

    public static final String TCP_PORT = "port";

    public static final String TCP_TIMEOUT_CONN = "timeout_conn";

    public static final String TCP_TIMEOUT_READ = "timeout_read";


    public Socket(Map configMap) {
        this.configMap = configMap;
        this.ip = (String) configMap.get("ip");
        this.port = (Integer) configMap.get("port");
        this.timeout_conn = (Integer) configMap.get("timeout_conn");
        this.timeout_read = (Integer) configMap.get("timeout_read");
    }

    public byte[] doReuquest(byte[] data, SocketProcessor socketProcessor) {
        java.net.Socket client = null;
        OutputStream dataOutputStream = null;
        DataInputStream dataInputStream = null;
        try {

            client = new java.net.Socket();

            client.connect(new InetSocketAddress(ip, Integer.valueOf(port)), Integer.valueOf(timeout_conn));
            client.setSoTimeout(timeout_read);
            dataOutputStream = client.getOutputStream();
            InputStream inputStream = client.getInputStream();
            dataInputStream = new DataInputStream(inputStream);
            byte[] requestData = socketProcessor.writeTcpHeader(data);
            dataOutputStream.write(requestData);
            dataOutputStream.flush();

            byte[] bb = socketProcessor.readTcpResponse(dataInputStream);
            return bb;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (dataInputStream != null) {
                    dataInputStream.close();
                }
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
